import { Swiper, SwiperSlide } from "swiper/react";
import { Autoplay } from "swiper/modules";
import "swiper/css";
import styles from "@/assets/scss/index.module.scss";
import React, { useEffect, useRef, useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import { Image, Pagination, Empty, Calendar, List, Avatar } from "antd";
import axios from "axios";
import dayjs from 'dayjs';
import { HolidayUtil, Lunar } from 'lunar-typescript';
import { UserOutlined, PhoneOutlined, QqOutlined, TwitchOutlined } from "@ant-design/icons";

function HomePages() {
    const [bolgList, setBolgList] = useState([]);
    const [pages, setPages] = useState({
        page: 1,
        pageSize: 20,
        totalPage: 0,
        totalSize: 0
    });
    const loading = $.loading();

    const loadData = async (pageNum = 1) => {
        loading.show();
        try {
            let response = await axios.post(`${$.baseUrl}/api/article/list`, {
                pages: {
                    page: pageNum,
                    pageSize: 10
                },
                querys: {
                    "ARTICLE_STATUS": 1,
                    "ARTICLE_TYPE": [1,2,11,12,13,14]
                }
            });
            const Rows = response.data;
            if (Rows.success) {
                setBolgList(Rows.data.list || []);
                setPages({
                    page: Rows.data.page,
                    pageSize: Rows.data.pageSize,
                    totalPage: Rows.data.totalPage,
                    totalSize: Rows.data.total
                });
            };
        } catch (error) {
            loading.hide();
            alert(error.message);
        } finally {
            loading.hide();
        }
    };

    useEffect(() => {
        loadData();
    }, []);

    const handlePageChange = (pageNum) => {
        loadData(pageNum);
    };

    return (
        <div className="m-t-20 p-b-48">
            <BannerPages />
            <div className={`${styles.main} rowStartStart p-t-48`}>
                <LeftPages articleData={bolgList} pages={pages} onPageChange={handlePageChange} />
                <RightPages/>
            </div>
        </div>
    )
};

// banner图
function BannerPages() {
    return (
        <div className={styles.banner}>
            <div className={`${styles.main} rela`}>
                <Swiper
                    className="fullScreen"
                    loop={true}
                    autoplay={{
                        delay: 30000
                    }}
                    modules={[Autoplay]}
                >
                    <SwiperSlide className="p-r-10 p-l-10">
                        <Link className={`${styles['slide-link']} fullScreen rela`}>
                            <Image src="/src/assets/imgs/banner1.jpg" preview={false} className={styles["slide-image"]}></Image>
                            <div className={styles['slide-content']}>
                                <div className={`${styles["dancing-script"]} dancing-script font-24 lineHeight-48`}>Odyssey</div>
                                <div className={`${styles['slide-text']} font-24 lineHeight-32 line-2`}>
                                    <span>在远方那未知的天地里，探寻并遇见那个隐藏着不同可能的自己</span>
                                </div>
                                <div className={`rowCenterCenter m-t-12 ${styles.color3}`}>
                                    <div className={`${styles['slide-name']} font-18 lineHeight-32`}>王绍祥</div>
                                    <div className="font-18 m-l-20 lineHeight-32">2025年09月28日</div>
                                </div>
                            </div>
                        </Link>
                    </SwiperSlide>
                    <SwiperSlide className="p-r-10 p-l-10">
                        <Link className={`${styles['slide-link']} fullScreen rela`}>
                            <Image src="/src/assets/imgs/banner2.jpg" preview={false} className={styles["slide-image"]}></Image>
                            <div className={styles['slide-content']}>
                                <div className={`${styles["dancing-script"]} dancing-script font-24 lineHeight-48`}>​Architect</div>
                                <div className={`${styles['slide-text']} font-24 lineHeight-32 line-2`}>
                                    <span>键盘敲击的不只是指令，更是用技术诗篇谱写未来世界的命运交响</span>
                                </div>
                                <div className={`rowCenterCenter m-t-12 ${styles.color3}`}>
                                    <div className={`${styles['slide-name']} font-18 lineHeight-32`}>王绍祥</div>
                                    <div className="font-18 m-l-20 lineHeight-32">2025年09月28日</div>
                                </div>
                            </div>
                        </Link>
                    </SwiperSlide>
                    <SwiperSlide className="p-r-10 p-l-10">
                        <Link className={`${styles['slide-link']} fullScreen rela`}>
                            <Image src="/src/assets/imgs/banner3.jpg" preview={false} className={styles["slide-image"]}></Image>
                            <div className={styles['slide-content']}>
                                <div className={`${styles["dancing-script"]} dancing-script font-18 lineHeight-48`}>Elysium</div>
                                <div className={`${styles['slide-text']} font-24 lineHeight-36 line-2`}>
                                    <span>当虚拟世界的规则成为自由的画布，便是游戏精神的终极绽放</span>
                                </div>
                                <div className={`rowCenterCenter m-t-12 ${styles.color3}`}>
                                    <div className={`${styles['slide-name']} font-14 lineHeight-32`}>王绍祥</div>
                                    <div className="font-14 m-l-20 lineHeight-32">2025年09月28日</div>
                                </div>
                            </div>
                        </Link>
                    </SwiperSlide>
                    <SwiperSlide className="p-r-10 p-l-10">
                        <Link className={`${styles['slide-link']} fullScreen rela`}>
                            <Image src="/src/assets/imgs/banner4.jpg" preview={false} className={styles["slide-image"]}></Image>
                            <div className={styles['slide-content']}>
                                <div className={`${styles["dancing-script"]} dancing-script font-24 lineHeight-48`}>Gastronomy</div>
                                <div className={`${styles['slide-text']} font-24 lineHeight-32 line-2`}>
                                    <span>味蕾绽放的巅峰时刻，恰是生命能量最绚烂的礼赞</span>
                                </div>
                                <div className={`rowCenterCenter m-t-12 ${styles.color3}`}>
                                    <div className={`${styles['slide-name']} font-18 lineHeight-32`}>王绍祥</div>
                                    <div className="font-18 m-l-20 lineHeight-32">2025年09月28日</div>
                                </div>
                            </div>
                        </Link>
                    </SwiperSlide>
                </Swiper>
            </div>
        </div>
    )
};

// 左边列表
function LeftPages({ articleData, pages, onPageChange }) {
    const navigate = useNavigate();
    const itemRender = (_, type, originalElement) => {
        if (type === "prev") {
            return <a>上一页</a>
        };
        if (type === "next") {
            return <a>下一页</a>
        };
        return originalElement;
    };
    const routers = (id) => {
        navigate("/details?ID=" + id);
    };
    return (
        <div className={styles.left}>
            {articleData.length === 0 ? (
                <div className={`${styles.empty} rowCenterCenter`}>
                    <Empty />
                </div>
            ) : (
                articleData.map((item, index) => {
                    return (
                        <div className={`${styles.item} rowStartCenter`} key={index} onClick={() => {routers(item.ARTICLE_ID)}}>
                            <div className={styles["item-cover"]}>
                                <Image src={`${$.baseUrl}/public/imgs/other/${item.ARTICLE_COVER}`} preview={false} className={styles["item-image"]}></Image>
                            </div>
                            <div className={`${styles["item-content"]} flex-1 columnCenterStart`}>
                                <div className={`font-20 lineHeight-48 line-1 ${styles['item-title']}`}>{item.ARTICLE_TITLE}</div>
                                <div className={`font-16 lineHeight-32 line-2 ${styles['item-brochure']}`}>{item.ARTICLE_BROCHURE}</div>
                                <div className={`font-16 lineHeight-32 rowStartCenter ${styles['item-author']}`}>
                                    <div className="m-r-8">{item.ARTICLE_AUTHOR}</div>
                                    <div className="m-l-8">{item.CREATED_AT}</div>
                                </div>
                            </div>
                        </div>
                    )
                })
            )}
            {articleData.length > 0 ? (
                <div className={`rowCenterCenter m-t-48 ${styles.pages}`}>
                    <Pagination total={pages.totalSize} current={pages.page} itemRender={itemRender} showTotal={(total, range) => {
                        return (
                            <div className="m-r-16">共 {pages.totalPage} 页， {pages.totalSize} 条数据</div>
                        )
                    }} onChange={(page, pages) => { onPageChange(page) }} pageSize={pages.pageSize}></Pagination>
                </div>
            ) : (
                <div></div>
            )}
        </div>
    );
};

// 右边
function RightPages() {
    return (
        <div className={`${styles.right} p-l-32`}>
            <div className={styles.wrapper}>
                <CreateCalendar></CreateCalendar>
            </div>
            <div className={`${styles["author-profile"]} m-t-32`}>
                <List itemLayout="horizontal">
                    <List.Item>
                        <List.Item.Meta avatar = {<Avatar icon = {<UserOutlined/>}/>} title = {"浪卐流"}></List.Item.Meta>
                    </List.Item>
                    <List.Item>
                        <List.Item.Meta avatar = {<Avatar icon = {<PhoneOutlined />}/>} title = {"17798421645"}></List.Item.Meta>
                    </List.Item>
                    <List.Item>
                        <List.Item.Meta avatar = {<Avatar icon = {<QqOutlined />}/>} title = {"2838719568"}></List.Item.Meta>
                    </List.Item>
                    <List.Item>
                        <List.Item.Meta avatar = {<Avatar icon = {<TwitchOutlined />}/>} title = {"2838719568@qq.com"}></List.Item.Meta>
                    </List.Item>
                </List>
            </div>
        </div>
    )
};

// 日历
function CreateCalendar() {
    const [selectDate, setSelectDate] = React.useState(() => dayjs());
    const [panelDate, setPanelDate] = React.useState(() => dayjs());

    const onDateChange = (value, selectInfo) => {
        if (selectInfo.source === 'date') {
            setSelectDate(value);
        }
    };

    const cellRender = (date, info) => {
        const d = Lunar.fromDate(date.toDate());
        const lunar = d.getDayInChinese();
        const solarTerm = d.getJieQi();
        const isWeekend = date.day() === 6 || date.day() === 0;
        const h = HolidayUtil.getHoliday(date.get('year'), date.get('month') + 1, date.get('date'));
        const displayHoliday = h?.getTarget() === h?.getDay() ? h?.getName() : undefined;

        if (info.type === 'date') {
            return React.cloneElement(info.originNode, {
                ...info.originNode.props,
                className: `${styles.dateCell} ${selectDate.isSame(date, 'date') ? styles.current : ''
                    } ${date.isSame(dayjs(), 'date') ? styles.today : ''
                    }`,
                children: (
                    <div className={styles.text}>
                        <span
                            className={`${isWeekend ? styles.weekend : ''
                                } ${!panelDate.isSame(date, 'month') ? 'gray' : ''
                                }`}
                        >
                            {date.get('date')}
                        </span>
                        {info.type === 'date' && (
                            <div className={styles.lunar}>{displayHoliday || solarTerm || lunar}</div>
                        )}
                    </div>
                ),
            });
        }
    };

    const headerRender = ({ value, type, onChange, onTypeChange }) => {};
    return (
        <Calendar fullCellRender={cellRender} fullscreen={false} onSelect={onDateChange} headerRender={headerRender} locale={{
            lang: {
                locale: "zh-cn",
                shortWeekDays: ["周日", "周一", "周二", "周三", "周四", "周五", "周六"]
            }
        }} />
    );
};

export default HomePages;